#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
双色球增强版LSTM-CRF模型训练脚本
在训练时融合序列LSTM预测作为算子，并使用模式记忆网络模式的预测结果作为权重因子
"""

import os
import sys
import torch
from datetime import datetime

# 添加项目根目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, '..', '..'))
sys.path.append(project_root)

# 临时添加算法目录到路径
algorithms_path = os.path.join(project_root, 'algorithms')
sys.path.append(algorithms_path)

from algorithms.enhanced_lstm_crf import create_and_train_enhanced_lstm_crf

def train_enhanced_lstm_crf_model():
    """训练双色球增强版LSTM-CRF模型"""
    print("[START] 开始训练双色球增强版LSTM-CRF模型")
    print("=" * 60)
    
    # 配置路径
    data_file = os.path.join(project_root, 'scripts', 'ssq', 'ssq_history.csv')
    sequence_lstm_model_path = os.path.join(project_root, 'scripts', 'ssq', 'ssq_lstm_model.pth')
    model_save_path = os.path.join(project_root, 'scripts', 'ssq', 'enhanced_lstm_crf_model.pth')
    
    # 检查必要的文件是否存在
    if not os.path.exists(data_file):
        print(f"[ERROR] 历史数据文件不存在: {data_file}")
        print("请先运行主程序获取双色球历史数据")
        return False
    
    if not os.path.exists(sequence_lstm_model_path):
        print(f"[ERROR] 序列LSTM模型文件不存在: {sequence_lstm_model_path}")
        print("请先训练序列LSTM模型")
        return False
    
    print(f"[DATA] 数据文件: {data_file}")
    print(f"[MODEL] 序列LSTM模型: {sequence_lstm_model_path}")
    print(f"[SAVE] 模型保存路径: {model_save_path}")
    
    try:
        # 创建并训练增强版LSTM-CRF模型
        trainer = create_and_train_enhanced_lstm_crf(
            csv_file_path=data_file,
            sequence_lstm_model_path=sequence_lstm_model_path,
            model_save_path=model_save_path,
            lottery_type='ssq'  # 指定彩票类型为双色球
        )
        
        if trainer is not None:
            print("[OK] 双色球增强版LSTM-CRF模型训练成功！")
            return True
        else:
            print("[ERROR] 双色球增强版LSTM-CRF模型训练失败！")
            return False
            
    except Exception as e:
        print(f"[ERROR] 训练过程出错: {e}")
        import traceback
        print(traceback.format_exc())
        return False

def main():
    """主函数"""
    print("[TARGET] 双色球增强版LSTM-CRF模型训练程序")
    print(f"[TIME] 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    success = train_enhanced_lstm_crf_model()
    
    print()
    if success:
        print("[SUCCESS] 训练完成！")
    else:
        print("[FAIL] 训练失败！")
    
    print(f"[TIME] 结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

if __name__ == "__main__":
    main()